package com.link.base.base.accntconsumer.controller;

import com.link.base.base.accnt.model.*;
import com.link.base.base.accntconsumer.model.AccountConsumer;
import com.link.base.base.accntconsumer.service.AccountConsumerService;
import com.link.base.base.mpconfig.model.Mp;
import com.link.base.base.mpconfig.service.MpService;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.service.SaleOrderService;
import com.link.base.base.reception.model.Reception;
import com.link.base.base.reception.service.ReceptionService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 消费者
 *
 * @author 曲元涛
 * @date 2020-07-01 18:12:52
 */
@Controller
@RequestMapping("/link/accountConsumer")
public class AccountConsumerController extends BasicController<AccountConsumer> {

    @Resource
    private AccountConsumerService accountConsumerService;
    @Resource
    private ReceptionService receptionService;
    @Resource
    private SaleOrderService saleOrderService;
    @Resource
    private MpService mpService;
    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicService<AccountConsumer> getBasicService() throws Exception {
        return accountConsumerService;
    }

    /**
     * 插入 消费者，消费者地址，消费者标签
     * @author 景隆东
     * @param accntline 消费者
     * @date 2020-02-17
     */
    @RequestMapping(value = "/moreModelInsert")
    @ResponseBody
    public Map<String, Object> moreModelInsert(@JsonParam AccountConsumer accntline) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accntline.setId(keyGenerateService.keyGenerate());
            accountConsumerService.moreModelInsert(accntline);
            result.put("success", true);
            result.put("accntId", accntline.getId());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
        }
        return result;
    }

    /**
     * 根据条件查询消费者
     *
     * @author 顾桂山
     * @date 2020-02-17 17:59:34
     */
    @RequestMapping(value = "/queryUniqueByExample", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByMobilePhone(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            AccountConsumer consumer = accountConsumerService.queryUniqueByExample(record);
            result.put("result", consumer);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取虚拟消费者
     *
     * @param corpid 账套ID
     * @return 虚拟消费者ID
     */
    @RequestMapping(value = "/virtualAccount")
    @ResponseBody
    public String virtualAccount(@RequestParam(value = "corpid") Long corpid) {
        return accountConsumerService.getVirtualAccount(corpid);
    }

    /**
     * 检查消费者记录
     *
     * @param record 消费者
     */
    @RequestMapping(value = "/checkAccount")
    @ResponseBody
    public Map<String, Object> checkAccount(@RequestBody AccountConsumer record) {
        // 门店+手机号码不存在时，先新建消费者记录，再将订单头上的客户Id赋值为该客户Id
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            AccountConsumer account = accountConsumerService.checkAccount(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询客户标签组信息
     *
     * @author lizt
     * 2017年5月18日
     */
    @RequestMapping(value = "/queryQdAccntTagGroups", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryQdAccntTagGroups(@JsonParam TagGroup record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<TagItem> list = accountConsumerService.queryQdAccntTagGroups(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询客户标签信息
     *
     * @author lizt
     * 2017年5月18日
     */
    @RequestMapping(value = "/queryQdAccntTags", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryQdAccntTags(@JsonParam TagItem record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<TagItem> list = accountConsumerService.queryQdAccntTags(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 通过ID查询客户标签信息
     *
     * @author lizt
     * 2017年3月27日
     * app 整合
     */
    @RequestMapping(value = "/queryTagsByAccntId", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryTagsById(TagItem record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<TagItem> list = accountConsumerService.queryTagsById(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 更新客户标签
     *
     * @author lizt
     * 2017年3月28日
     */
    @RequestMapping(value = "/updateTagList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateTagList(@RequestBody ListOfTags list) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountConsumerService.updateTagList(list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 插入中间表
     *
     * @param entity 客户-识别顾客中间表对象
     * @author : LiQun
     * @date : 下午3:57 2018/5/7
     */
    @RequestMapping(value = "/accountPersonInsert")
    @ResponseBody
    public Map<String, Object> accountPersonInsert(@RequestBody AccountPerson entity) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            accountConsumerService.accountPersonInsert(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 清空客户微信seq
     *
     * @author changwj
     * 2017年4月22日
     */
    @RequestMapping(value = "/emptyAccntSeq", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> emptyAccntSeq(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            //清空客户头像url及更多信息
            accountConsumerService.emptyAccntSeq(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 客户历程
     * @param entity 消费者
     */
    @ResponseBody
    @RequestMapping(value = "/queryAccountExperience")
    public Map<String, Object> queryAccountExperience(@JsonParam AccountConsumer entity) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<AccountExperience> list = new ArrayList<AccountExperience>();
            // 客户id
            Long accountId = entity.getId();
            if (null != accountId) {
                // 获取接待列表
                Reception opty = new Reception();
                opty.setAccountId(accountId);
                List<Reception> optyList = receptionService.queryAll(opty);

                AccountExperience accountExperience = null;

                for (Reception reception : optyList) {
                    accountExperience = new AccountExperience();
                    accountExperience.setType("reception");
                    accountExperience.setRelatedId(reception.getId());
                    accountExperience.setGuideName(reception.getShoppingGuide());
                    accountExperience.setCreated(reception.getCreated());
                    accountExperience.setDealOrderStatus(reception.getDealOrderStatus());
                    accountExperience.setLeaveStoreReasonList(reception.getLeaveStoreReasonList());
                    list.add(accountExperience);
                }

                // 获取订单列表
                SaleOrder order = new SaleOrder();
                order.setAcctId(accountId);
                List<SaleOrder> orderList = saleOrderService.queryAll(order);

                for (SaleOrder saleOrder : orderList) {
                    accountExperience = new AccountExperience();
                    accountExperience.setType("order");
                    accountExperience.setRelatedId(saleOrder.getId());
                    accountExperience.setCreated(saleOrder.getOrderDate());
                    accountExperience.setOrderSource(saleOrder.getSourceFrom());
                    accountExperience.setSaleOrderItemList(saleOrder.getSaleOrderItemList());
                    accountExperience.setOrderStatus(saleOrder.getStatus());
                    accountExperience.setCreated(saleOrder.getCreated());
                    list.add(accountExperience);
                }

            }
            final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            list.sort((o1, o2) -> {
                try {
                    Date date1 = sdf.parse(o1.getCreated());
                    Date date2 = sdf.parse(o2.getCreated());
                    return date2.compareTo(date1);
                } catch (ParseException e) {
                    LCLogger.withException(e);
                }
                return 0;
            });
            result.put("rows", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 修改消费者信息
     *
     * @author : LiQun
     * @date : 2018/10/9
     */
    @RequestMapping(value = "/modifyConsumer", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> modifyConsumer(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            result = accountConsumerService.modifyConsumer(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 当传入经纬度时查询配置的附件门店的距离参数值
     * lujiang
     */
    @Override
    public void beforQueryExample(AccountConsumer entity, HttpServletRequest request) throws Exception {
        CoreUser user = UserUtil.getUser();
        //当查询参数有经纬度的时候查询配置信息，如果没有配置信息抛出异常
        if (null != entity.getLongitude() && !("").equals(entity.getLongitude())) {
            //获取Mp对象
            Mp mp = new Mp();
            mp.setAppId(user.getMpAppId());
            mp.setPageFlag(false);
            List<Mp> mpList = mpService.queryByExamplePage(mp);
            if (mpList.size() > 0) {
                mp = mpList.get(0);
            } else {
                throw new ServiceException("ACCT-047");
            }
            if (null == mp || null == mp.getLimitDistance()) {
                throw new ServiceException("ACCT-048");
            }
            Double distance = Double.parseDouble(mp.getLimitDistance()) * 1000;
            entity.setDistance(distance);
        }
        super.beforQueryExample(entity, request);
    }

    /**
     * 导购助手-更新客户信息
     * 使用标准方法由于存在listOfTags字段,导致无法保存
     * 调用方法直接调用标准update
     *
     * @author : LiQun
     * @date : 2018/10/31
     */
    @RequestMapping(value = "/guideAccountUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> guideAccountUpdate(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountConsumerService.update(record);
            record = accountConsumerService.queryById(record);
            result.put("success", true);
            result.put("result", record);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 微信加密数据解密
     *
     * @param record 查询数据
     * @return result 解密的数据
     * @author KuangRuifeng
     * @date 2018年11月29日
     */
    @RequestMapping(value = "/decryptWxData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> decryptWxData(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Map<String, Object> decryptData = accountConsumerService.decryptWxData(record);
            result.put("success", true);
            result.put("result", decryptData);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 小程序获取到手机号码后更新消费者
     *
     * @author KuangRuifeng
     * @date 2018/12/18
     */
    @RequestMapping(value = "/updMobilePhoneInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updMobilePhoneInfo(@RequestBody AccountConsumer record, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (StringUtils.isBlank(record.getMobilePhone())) {
                throw new ServiceException("PUBLIC-009");
            }
            result = accountConsumerService.updMobilePhoneInfo(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询访客信息
     *
     * @param entity 消费者
     * @author 路江
     */
    @RequestMapping(value = "/queryAcctAndMember", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctAndMember(@RequestBody AccountConsumer entity) {
        Map<String, Object> result = new HashMap<>(4);
        AccountConsumer account;
        try {
            account = accountConsumerService.queryAcctAndMember(entity);
            result.put("rows", account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 营销助手未登录状态下分享
     *
     * @author 旷锐锋
     * @date 2019/2/21
     */
    @RequestMapping({"/notLogin/queryById"})
    @ResponseBody
    public Map<String, Object> query(@JsonParam AccountConsumer account, HttpSession session,
                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            // 未登录状态下，模拟登录，处理特殊逻辑
            account.setImitateLogin("Y");
            result = super.queryById(account, session, request, response);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 判断当前小程序用户尝试登陆使用的手机号码是否合法
     *
     * @author KuangRuifeng
     * @date 2019/3/14
     */
    @RequestMapping(value = "/checkMPLoginPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkMPLoginPhone(@RequestBody AccountConsumer record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (StringUtils.isBlank(record.getMobilePhone())) {
                throw new ServiceException("PUBLIC-009");
            }
            result = accountConsumerService.checkMpLoginPhone(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 通过openid查询消费者
     * @author Hlj
     * @date 2019年03月24日
     */
    @RequestMapping(value = "/queryConsumerByOpenId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryConsumerByOpenId(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            // 如果前端没有传入openid,则从user中取
            if (StringUtils.isBlank(record.getWxOwnOpenId())) {
                CoreUser user = UserUtil.getUser();
                record.setWxOwnOpenId(user.getOpenId());
            }
            AccountConsumer account = accountConsumerService.queryConsumerByOpenId(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据一个消费者信息，带出消费者对应所有会员(或电话号码)信息
     * @author wangdawei
     * Attr1标记是根据会员查还是根据电话号码查
     * @author Hlj
     * @date 2019年03月24日
     */
    @RequestMapping(value = "/queryAcctListById", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctListById(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            List<AccountConsumer> accountList = accountConsumerService.queryAcctListById(record);
            result.put("success", true);
            result.put("result", accountList);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建消费者，对接DMP新建消费者接口，由DMP返回渠道消费者及父消费者（可无）
     * 再将返回信息保存至link数据库
     *
     * @author NingLanhao
     * @param entity 消费者
     * @date 2019-03-26 11:04
     * @throws Exception 异常
     */
    @RequestMapping(value = "/checkChannelConsumer", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkChannelConsumer(@RequestBody AccountConsumer entity) throws Exception {
        Map<String, Object> result = new HashMap<>(4);
        try {
            AccountConsumer account = accountConsumerService.checkChannelConsumer(entity);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage() + "(BASE-ACT-001)");
        }
        return result;
    }

    /**
     * 微信更新消费者信息
     *
     * @author huanglongjian
     * @date 2019-10-22 14:17
     * @param record 消费者
     */
    @RequestMapping(value = "/wxUpdateAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> wxUpdateAccount(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            AccountConsumer account = accountConsumerService.wxUpdateAccount(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 消费者批量分配跟进
     *
     * @param entity -id 消费者主键
     * @param entity -postnId 被分配人职位ID
     */
    @RequestMapping(value = "/accntDistribution", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> acctDistribution(@RequestBody AccountConsumer entity) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            Long id = entity.getId();
            Long distributionId = entity.getPostnId();
            if (id == null || distributionId == null) {
                result.put("success", false);
                result.put("result", "传入参数有误");
                result.put("postnId", "");
                return result;
            }
            AccountConsumer account = accountConsumerService.queryById(id);
            if (account == null) {
                result.put("success", false);
                result.put("result", "id[" + id + "]无渠道消费者");
                result.put("postnId", "");
                return result;
            }
            String unassigned = "Unassigned";
            Long postnId = account.getPostnId();
            // todo: 确定是一个什么子类型？ String subAcctType = account.getSubAcctType();
            String subAcctType = "";
            if (StringUtils.isBlank(subAcctType) || StringUtils.equals(unassigned, subAcctType)) {
                account.setPostnId(distributionId);
                account.setRow_status(BasicService.ROW_STATUS_UPDATE);
                // 原来是getMobilePhone1
                account.setMobilePhone(account.getMobilePhone());
                account.setAcctName(account.getAcctNameSecret());
                AccountConsumer returnAccount = accountConsumerService.saveAccountToDmp(account);
                result.put("success", true);
                result.put("result", returnAccount);
                result.put("postnId", "");
                return result;
            } else {
                result.put("success", true);
                String fstName = account.getFstName();
                result.put("result", fstName);
                result.put("postnId", postnId);
                return result;
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("postnId", "");
        }
        return result;
    }

    /**
     * 个人信息更新
     *
     * @author : 顾桂山
     * @date : 2020/02/18
     */
    @RequestMapping(value = "/updateConsumer", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateAccount(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountConsumerService.updateConsumer(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 根据手机号生成消费者
     *
     * @author 杨锐
     * @date 2020-02-21 21:30:34
     */
    @RequestMapping(value = "/newConsumerByPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> newConsumerByPhone(@RequestBody AccountConsumer record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            AccountConsumer consumer = accountConsumerService.newConsumerByPhone(record);
            result.put("result", consumer);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 根据大客户ID查询对应统一消费者的标签
     *
     * @author 曲元涛
     * @date 2020/3/10 11:36
     * @param accountConsumer 大客户
     */
    @PostMapping(value = "/queryTagByVipConsumerId")
    @ResponseBody
    public Map<String, Object> queryTagByVipConsumerId(@RequestBody AccountConsumer accountConsumer) {
        Map<String, Object> result = new HashMap<>(3);
        try {
            Long vipConsumerId = Optional.ofNullable(accountConsumer)
                    .map(AccountConsumer::getId)
                    .orElseThrow(() -> new BasicControllerException("请传入大客户ID"));
            accountConsumer = accountConsumerService.queryById(vipConsumerId);
            Long uniqueConsumerId = Optional.ofNullable(accountConsumer)
                    .map(AccountConsumer::getAcctParentId)
                    .orElse(-1L);
            if (-1L == uniqueConsumerId) {
                result.put("rows", new ArrayList<>());
                result.put("success", true);
                result.put("total", 0L);
                return result;
            }
            result = accountConsumerService.queryConsumerTag(uniqueConsumerId);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.error().withMessageKey("queryTagByVipConsumerId:")
                    .withMessage("根据大客户ID查询标签失败：" + e.getMessage()).flush();
        }
        return result;
    }
}